package 二叉树的所有路径;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhengTao
 * @version 1.0
 * @description:  二叉树的所有路径     递归加回溯
 * @date 2022/11/2 12:25
 */
public class Demo257 {
    public List<String> binaryTreePaths(TreeNode root) {
        //结果集
        List<String> res=new ArrayList<>();
        //头节点为空，直接返回结果
        if(root==null){
            return res;
        }
        //单条路径
        List<String> singlePath=new ArrayList<>();
        //回溯
        backTrack(root,res,singlePath);
        return res;

    }
    //递归三部曲，确定参数和返回值
    private void backTrack(TreeNode root, List<String> res, List<String> singlePath) {
           //终止条件
        singlePath.add(String.valueOf(root.val));
        if(root.left==null&&root.right==null){
            String collect = String.join("->", singlePath);
            res.add(collect);
            return;
        }
        if(root.right!=null){
            //递归
            backTrack(root.right,res,singlePath);
            //回溯
            singlePath.remove(singlePath.size()-1);
        }
        if(root.left!=null){
            //递归
            backTrack(root.left,res,singlePath);
            //回溯
            singlePath.remove(singlePath.size()-1);
        }

    }

    //Definition for a binary tree node.
     public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
     this.val = val;
     this.left = left;
     this.right = right;
     }
     }

}
